﻿app.controller('NotificationController', function ($scope, $timeout, $rootScope, $routeParams, notificationFactory, friendFactory, messageFactory, roomFactory, $location, fileFactory) {
    init();

    function init() {
        $scope.severName = mainFileAddress;
        $scope.roleByGroup = JSON.parse(localStorage.getItem("menu"));

        //count--------------
        notificationFactory.countAddFriend(localStorage.getItem("idkey")).success(function (data) {
            $scope.countAddFriend = data;
        });
        notificationFactory.countFromRoom(localStorage.getItem("idkey")).success(function (data) {
            $scope.countFromRoom = data;
        });
        notificationFactory.countNewMessage(localStorage.getItem("idkey")).success(function (data) {
            $scope.countNewMessage = data;
        });

        $scope.ready = true;
        //load item----------
        $scope.addfriend = false;
        $scope.showHideAddFriend = function () {
            if ($scope.addfriend == false)
                notificationFactory.getAddFriend(localStorage.getItem("idkey")).success(function (data) {
                    $scope.getAddFriend = data;
                });
            $scope.addfriend = !$scope.addfriend;
        };


        $scope.newcomment = false;
        $scope.showHideNewComment = function () {
            if ($scope.newcomment == false)
                notificationFactory.getNewComment(localStorage.getItem("idkey")).success(function (data) {
                    $scope.getNewComment = data;
                });
            $scope.newcomment = !$scope.newcomment;
        };


        $scope.newfromroom = false;
        $scope.showHideFromRoom = function () {
            if ($scope.newfromroom == false) {
                notificationFactory.getAcceptRoom(localStorage.getItem("idkey")).success(function (data) {
                    $scope.getAcceptRoom = data;
                });// đã vào phòng abc
                notificationFactory.getJoinRoom(localStorage.getItem("idkey")).success(function (data) {
                    $scope.getJoinRoom = data;
                });// từ user abc
            }
            $scope.newfromroom = !$scope.newfromroom;
        };

        friendFactory.getFriends(localStorage.getItem("idkey")).success(function (data) {
            $scope.friends = data;
        });
        $scope.endlistfriend = false;
        friendFactory.countFriends(localStorage.getItem("idkey")).success(function (data) {
            $scope.countfriends = data;
        });
        if ($scope.countfriends >= 5) {
            $scope.endlistfriend = true;
            $scope.countfriends -= 5;
        }
        //thao tác với danh sách notificaton----------------------------------------------------------
        $scope.deleteNotification = function (id) {
            $('#newComment_' + id).fadeOut();
            notificationFactory.deleteNotification(id);
            $scope.countNewMessage--;
        };
        $scope.acceptFriend = function (id) {
            $('#newFriend_' + id).fadeOut();
            notificationFactory.acceptFriend(id);
            $scope.countAddFriend--;
        };
        $scope.deleteAcceptFriend = function (id) {
            $('#newFriend_' + id).fadeOut();
            notificationFactory.deleteAcceptFriend(id);
            $scope.countAddFriend--;
        };
        $scope.deleteJoinRoom = function (id) {
            $('#joinRoom_' + id).fadeOut();
            notificationFactory.deleteJoinRoom(id);
            $scope.countFromRoom--;
        };
        $scope.joinRoom = function (user) {
            $('#joinRoom_' + user.Id).fadeOut();
            notificationFactory.joinRoom(user.Id).success(function () {
                notificationFactory.postNotification({ To: user.UserId, RoomId: user.RoomId, Type: notificationType.Accept });
                // $scope.countFromRoom--;
            });
        };
        $scope.deleteAcceptRoom = function (id) {
            $('#acceptRoom_' + id).fadeOut();
            notificationFactory.delAcceptRoom(id);
            $scope.countFromRoom--;
        };


        //message---------------------------------------------------------------------

        messageDuration();

        $scope.ready = true;

        $scope.messageData = { CommentText: "", CreateBy: null, RoomId: null, DateTime: null, UserId: localStorage.getItem("idkey") };
        $scope.createComment = function () {
            messageFactory.addMessage($scope.messageData).success(function () {
                $scope.messageData.CommentText = "";
                messageFactory.getMessageByFriend(localStorage.getItem("idkey")).success(function (data) {
                    $scope.MessageByUser = data;
                });
            });
        };
        //đính kèm
        $scope.selectPicture = function () {
            navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                quality: 50,
                destinationType: destinationType.DATA_URL,
                sourceType: pictureSource.PHOTOLIBRARY
            });
        };
        $scope.takePicture = function () {
            navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
                quality: 50,
                destinationType: destinationType.DATA_URL
            });
        };


        $scope.delComment = function (id) {
            messageFactory.delMessage(id).success(function (data) {
                if (data.Text != null) {
                    $("#mess_" + id).fadeOut();
                    messageFactory.getMessageByFriend(localStorage.getItem("idkey")).success(function (listmess) {
                        $scope.MessageByUser = listmess;
                    });
                    fileFactory.deleteFile({ Text: data.Text, Path: "Upload" });
                }

            });
        };



        //xem tung loai thong bao
        $scope.seeAllNewFriend = function () {
            window.location.href = '#/newFriend';
        };
        $scope.seeAllNewMessage = function () {
            window.location.href = '#/newMessage';
        };
        $scope.seeAllNewFromRoom = function () {
            window.location.href = '#/newFromRoom';
        };
        createMenu();
        $scope.status = false;
        disableLoadding();
        $scope.loadding = false;
        $scope.out = function () {
            logout();
        };
        //vào xem thông tin phòng
        $scope.goToRoom = function (userRoom) {
            roomFactory.getRoom(userRoom.RoomId).success(function (data) {
                $location.path("/lesson/" + userRoom.RoomId + "/" + data.CurrentLesson);
            });
        };
        // download
		$scope.downloadImg= function(name){
			var url= $scope.severName + "Upload/"+ name;
			$location.href = url;
		}
        $scope.downloadImageFile = function () {
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
                function onFileSystemSuccess(fileSystem) {
                    fileSystem.root.getFile(
                    "dummy.html", { create: true, exclusive: false },
                    function gotFileEntry(fileEntry) {
                        var sPath = fileEntry.fullPath.replace("dummy.html", "");
                        var fileTransfer = new FileTransfer();
                        fileEntry.remove();

                        fileTransfer.download(
                            "http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
                            sPath + "theFile.pdf",
                            function (theFile) {
                                console.log("download complete: " + theFile.toURI());
                                showLink(theFile.toURI());
                            },
                            function (error) {
                                console.log("download error source " + error.source);
                                console.log("download error target " + error.target);
                                console.log("upload error code: " + error.code);
                            }
                        );
                    }, fail);
                }, fail);
        };
    }
    function messageDuration() {
        messageFactory.getMessageByFriend(localStorage.getItem("idkey")).success(function (data) {
            $scope.MessageByUser = data;
        });
        if ($location.path() == "/notification")
            $timeout(messageDuration, 5000, true);
    }

    function onFail() { }

    function onPhotoDataSuccess(imageData) {
        fileFactory.uploadFile({ Text: imageData, Path: "Upload" }).success(function (data) {
            var item = { CommentText: "", Atack: data.Text, CreateBy: null, RoomId: null, DateTime: null, UserId: localStorage.getItem("idkey") };
            messageFactory.addMessage(item).success(function () {
                messageFactory.getMessageByFriend(localStorage.getItem("idkey")).success(function (listmess) {
                    $scope.MessageByUser = listmess;
                });
            });
        });
    }

    function showLink(url) {
        alert(url);
        var divEl = document.getElementById("ready");
        var aElem = document.createElement("#kq");
        aElem.setAttribute("target", "_blank");
        aElem.setAttribute("href", url);
        aElem.appendChild(document.createTextNode("Ready! Click To Open."))
        divEl.appendChild(aElem);

    }


    function fail() {
        //console.log(evt.target.error.code);
    }

});














function disableLoadding() {
    $("#preloader").fadeOut(1000);
}
function logout() {
    localStorage.removeItem("idkey");
    localStorage.removeItem("authen");
    localStorage.removeItem("menu");
    window.location.href = '#/login';
}
function createMenu() {
    var snapper = new Snap({
        element: document.getElementById('content')
    });
    $('.deploy-sidebar, .close-icon').click(function () {
        if (snapper.state().state == "left") {
            snapper.close();
        } else {
            snapper.open('left');
        }
        return false;
    });
    $('.page-content').click(function () {
        snapper.close();
    });
}
function toggle() {
    $('.show-toggle-v4').hide();
    $('.toggle-content-v4').hide();
    $('.show-toggle-v4').click(function () {
        $(this).hide();
        $(this).parent().find('.hide-toggle-v4').show();
        $(this).parent().find('.toggle-content-v4').fadeOut(100);
        return false;
    });
    $('.hide-toggle-v4').click(function () {
        $(this).parent().find('.show-toggle-v4').show();
        $(this).hide(); $(this).parent().find('.toggle-content-v4').fadeIn(200);
        return false;
    });

}